package com.ruoyi.web.controller.youtobe;

import com.ruoyi.youtobe.domain.VideoInfoVO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.List;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/11/5
 */
public class VideoExcelExporter {

    // 默认图片尺寸（像素）
    private static final int DEFAULT_IMAGE_WIDTH = 320;
    private static final int DEFAULT_IMAGE_HEIGHT = 180;

    /**
     * 创建包含图片和文字列的Excel
     */
    public static Workbook createExcelWithImagesAndText(List<VideoInfoVO> videoList,
                                                        int imageWidth,
                                                        int imageHeight) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("视频数据");

        // 创建样式
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle textStyle = createTextStyle(workbook);

        // 创建标题行
        createHeaderRow(sheet, headerStyle);

        // 设置列宽
        setupColumnWidths(sheet, imageWidth);

        // 填充数据和图片
        fillDataAndImages(sheet, videoList, textStyle, imageWidth, imageHeight);

        return workbook;
    }

    /**
     * 创建标题行样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /**
     * 创建文本样式
     */
    private static CellStyle createTextStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true); // 自动换行
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /**
     * 创建标题行
     */
    private static void createHeaderRow(Sheet sheet, CellStyle headerStyle) {
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(25); // 设置标题行高度

        String[] headers = {
                "视频ID", "默认标题", "中文标题", "英文标题",
                "播放量", "发布时间",  "封面图片"
        };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
    }

    /**
     * 设置列宽
     */
    private static void setupColumnWidths(Sheet sheet, int imageWidth) {
        sheet.setColumnWidth(0, 12 * 256);  // 视频ID
        sheet.setColumnWidth(1, 30 * 256);  // 视频标题
        sheet.setColumnWidth(2, 30 * 256);  // 中文标题
        sheet.setColumnWidth(3, 30 * 256);  // 英文标题
        sheet.setColumnWidth(4, 12 * 256);  // 播放量
        sheet.setColumnWidth(5, 20 * 256);  // 发布时间

        // 图片列宽度根据图片宽度计算
        int imageColumnWidth = ExcelImageUtils.calculateColumnWidth(imageWidth);
        sheet.setColumnWidth(6, imageColumnWidth * 256);
    }

    /**
     * 填充数据和图片
     */
    private static void fillDataAndImages(Sheet sheet, List<VideoInfoVO> videoList,
                                          CellStyle textStyle, int imageWidth, int imageHeight) throws Exception {
        CreationHelper helper = sheet.getWorkbook().getCreationHelper();

        for (int i = 0; i < videoList.size(); i++) {
            VideoInfoVO video = videoList.get(i);
            int rowIndex = i + 1; // 跳过标题行

            // 创建数据行
            Row row = sheet.createRow(rowIndex);

            // 填充文字数据
            fillTextData(row, video, textStyle);

            // 插入图片
            insertImage(sheet, video.getThumbnailUrl(), rowIndex, 6, imageWidth, imageHeight);

            // 设置行高以适应图片
            float rowHeight = ExcelImageUtils.calculateRowHeight(imageHeight);
            row.setHeightInPoints(rowHeight);
        }
    }

    /**
     * 填充文字数据
     */
    private static void fillTextData(Row row, VideoInfoVO video, CellStyle style) {
        // 视频ID
        Cell cell0 = row.createCell(0);
        cell0.setCellValue(video.getVideoId());
        cell0.setCellStyle(style);

        // 视频标题
        Cell cell1 = row.createCell(1);
        cell1.setCellValue(video.getDefaultTitle());
        cell1.setCellStyle(style);

        // 中文标题
        Cell cell2 = row.createCell(2);
        cell2.setCellValue(video.getChineseTitle() != null ? video.getChineseTitle() : "");
        cell2.setCellStyle(style);

        // 英文标题
        Cell cell3 = row.createCell(3);
        cell3.setCellValue(video.getEnglishTitle() != null ? video.getEnglishTitle() : "");
        cell3.setCellStyle(style);

        // 播放量
        Cell cell4 = row.createCell(4);
        cell4.setCellValue(video.getViewCount() != null ? video.getViewCount() : 0);
        cell4.setCellStyle(style);

        // 发布时间
        Cell cell5 = row.createCell(5);
        if (video.getPublishTime() != null) {
            cell5.setCellValue(video.getPublishTime().toString());
        }
        cell5.setCellStyle(style);


    }

    /**
     * 插入图片到指定位置
     */
    private static void insertImage(Sheet sheet, String imageUrl, int rowIndex,
                                    int colIndex, int targetWidth, int targetHeight) throws Exception {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return;
        }

        try {
            // 下载图片
            byte[] imageData = ExcelImageUtils.downloadImage(imageUrl);

            // 获取工作簿
            Workbook workbook = sheet.getWorkbook();

            // 添加图片到工作簿
            int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);

            // 创建绘图对象
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            // 创建锚点 - 精确定位图片
            ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();

            // 设置图片位置（从指定单元格开始）
            anchor.setCol1(colIndex);
            anchor.setRow1(rowIndex);
            anchor.setCol2(colIndex + 1);
            anchor.setRow2(rowIndex + 1);

            // 设置精确的图片尺寸（EMU单位）
            anchor.setDx1(0);
            anchor.setDy1(0);
            anchor.setDx2(ExcelImageUtils.pixelsToEMU(targetWidth));
            anchor.setDy2(ExcelImageUtils.pixelsToEMU(targetHeight));

            // 插入图片
            drawing.createPicture(anchor, pictureIdx);

            System.out.println("成功插入图片: " + imageUrl + " | 尺寸: " +
                    targetWidth + "×" + targetHeight + " 像素");

        } catch (Exception e) {
            System.err.println("插入图片失败: " + imageUrl + " | 错误: " + e.getMessage());
            // 在图片单元格显示错误信息
            Row row = sheet.getRow(rowIndex);
            if (row != null) {
                Cell imageCell = row.createCell(colIndex);
                imageCell.setCellValue("图片加载失败");
            }
        }
    }
}
